

package com.licw.zs.s397;

import java.util.Arrays;

class p4 {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(Arrays.toString(solution.findPermutation(new int[]{2, 1, 0})));
        System.out.println(Arrays.toString(solution.findPermutation(new int[]{1, 0, 2})));
        System.out.println(Arrays.toString(solution.findPermutation(new int[]{0, 2, 1})));
    }

    static
//leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int[] findPermutation(int[] nums) {
            int n = nums.length;
            int[] perm = new int[n];
            nums[0] = -1;
            for (int i = 1; i < n; i++) {
                int diff = Integer.MAX_VALUE, idx = -1;
                for (int j = 0; j < n; j++) {
                    if (nums[j] == -1) continue;
                    if (Math.abs(perm[i - 1] - nums[j]) < diff
                            || (Math.abs(perm[i - 1] - nums[j]) == diff && j < idx)) {
                        idx = j;
                        diff = Math.abs(perm[i - 1] - nums[j]);
                    }
                }
                perm[i] = idx;
                nums[idx] = -1;
            }
            return perm;
        }

    }
//leetcode submit region end(Prohibit modification and deletion)

}